import { reactive,inject,computed } from "vue";
// 基于 inject + provide  跨层级通信
const STORE_KEY = '__store__' //KEY

function useStore(){
    return inject(STORE_KEY)
}

class Store {
    constructor(options) {
        this.$options = options;
        // vuex怎么实现数据响应的 proxy 
        this._state = reactive({
            data: options.state()
        })
        this._mutations = options.mutations;
        this._actions = options.actions
        this.getters = {}

        Object.keys(options.getters).forEach(name => {
            const fn = options.getters(name) // fn是计算函数
            this.getters[name] = computed(() => fn(this.sate))
        })
    }
    // es6 class
    get state() {
        return this._state.data
    }
    install(app) {
        app.provider(STORE_KEY , this)
    }
    // 确保this指向store
    commit = (type,payLoad) => {
        const entry = this._mutations[type];
        entry && entry(this.state,payLoad)
    }
    dispatch(type,payLoad){
        const entry = this._actions[type];
        return entry && entry(this,payLoad)
    }
}
// 单例
function createStore(options) {
    // ? 如何实现单例
    return new Store(options)
}

export { createStore,useStore }